package com.kime.shiro.realms;

import com.kime.shiro.entity.Perms;
import com.kime.shiro.entity.Role;
import com.kime.shiro.entity.User;
import com.kime.shiro.salt.MyByteSource;
import com.kime.shiro.service.RoleService;
import com.kime.shiro.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: JiangYi
 * @Date: 2022-03-14 22:23:59
 * @Description: 自定义 Realm
 */
public class CustomerRealm extends AuthorizingRealm {

    // 因为 Realm 在 Shiro Config 中配置到 Bean 中，所以能够自动注入
    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // 获取身份信息
        String primaryPrincipal = (String) principalCollection.getPrimaryPrincipal();
        System.out.println("调用授权验证：" + primaryPrincipal);
        // 根据主身份信息获取角色和权限信息
//        if ("kimewen".equals(primaryPrincipal)) {
//            SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
//            simpleAuthorizationInfo.addRole("user");
//            simpleAuthorizationInfo.addStringPermission("user:find:*");
//            simpleAuthorizationInfo.addStringPermission("user:update:*");
//            return simpleAuthorizationInfo;
//        }
        User user = userService.findRolesByUserName(primaryPrincipal);
        // 授权角色信息
        List<Role> roles = user.getRoles();
        if (!CollectionUtils.isEmpty(roles)) {
            SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
            roles.forEach(role -> {
                simpleAuthorizationInfo.addRole(role.getName());
                // 权限信息 为了业务清晰这里使用在循环中查询数据库，可以进行优化
                List<Perms> perms = roleService.findPermsByRoleId(role.getId());
                if (!CollectionUtils.isEmpty(perms)) {
                    perms.forEach(perm -> {
                        simpleAuthorizationInfo.addStringPermission(perm.getName());
                    });
                }
            });
            return simpleAuthorizationInfo;
        }
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // 根据身份信息
        String principal = (String) authenticationToken.getPrincipal();
        // 在工厂中获取 service 对象
//        UserService userService = (UserService) ApplicationContextUtil.getBean("userService");
        User user = userService.findByUserName(principal);
//        if ("zhangsan".equals(principal)) {
//            return new SimpleAuthenticationInfo(principal, "123456", this.getName());
//        }
        if (!ObjectUtils.isEmpty(user)) {
            return new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), new MyByteSource(user.getSalt()), this.getName());
        }
        return null;
    }
}
